/*
 * Copyright (C) 2009 Rafael Fernandes
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.phonebooksharing.android.async;

import java.io.IOException;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.net.Uri;
import android.util.Log;

import com.phonebooksharing.android.provider.PhonebookSharingManager;
import com.phonebooksharing.android.provider.PhonebookSharing.Dashboard;
import com.phonebooksharing.android.provider.PhonebookSharing.Sync;
import com.phonebooksharing.android.services.DesktopDashboardUpdaterService;
import com.phonebooksharing.android.services.NotSharingUpdaterService;
import com.phonebooksharing.android.util.Global;
import com.phonebooksharing.android.util.LocationUtil;
import com.phonebooksharing.android.util.NetworkHandlerTask;
import com.phonebooksharing.dto.dashboard.DashboardItem;

//@SuppressWarnings("unchecked")
public abstract class DashboardUpdaterTask extends NetworkHandlerTask<Context, Object, Void> {
//    protected SharedPreferences pref;
    protected Location lastLocation;
    protected Context cx;

    @Override
    public Void doInBackground(Context... params) {
        this.cx = params[0];
        final ContentResolver cr = cx.getContentResolver();
//        pref = cx.getSharedPreferences(RecPreferencesActivity.PREF_NAME, Context.MODE_PRIVATE);
        cr.delete(Dashboard.CONTENT_URI, null, null); //delete all
        ContentValues cv;
        Uri syncInProgress = null;
        try {
            
            final Location l = LocationUtil.getCurrentLocation(cx);
            final String city = LocationUtil.getAddress(cx, l);

            //mark all that are processing as not complete for consistency only
            cv = new ContentValues();
            cv.put(Sync.SYNC_STATUS, Sync.STATUS_NOT_COMPLETED);
            cr.update(Sync.CONTENT_URI, cv, Sync.SYNC_STATUS + "=" + Sync.STATUS_PROCESSING, null);
            
            cv = new ContentValues();
            cv.put(Sync.SYNC_ADDRESS, city);
            cv.put(Sync.SYNC_LATITUDE, l.getLatitude());
            cv.put(Sync.SYNC_LONGITUDE, l.getLongitude());
            cv.put(Sync.SYNC_TIME, System.currentTimeMillis());
            syncInProgress = cr.insert(Sync.CONTENT_URI, cv);
            
            final String url = String.format(Global.DASHBOARD_SERVLET_URL, "u" /*ac*/, "" /*q*/, "" /*p*/, "" /*ps*/);
            final DashboardItem di = (DashboardItem)doNetworkPost(url, Global.authItem);
            
            cv = new ContentValues();
            cv.put(Dashboard.QTY_FRIENDS_NEARBY,     di.qtyFriendsNearby);
            cv.put(Dashboard.QTY_MESSAGES,           di.qtyFriendsMessages);
            cv.put(Dashboard.QTY_PHOTOS,             di.qtyFriendsPhotos);
            cv.put(Dashboard.QTY_PLACES_NEARBY,      di.qtyPlacesNearby);
            cv.put(Dashboard.QTY_POSTCARDS,          di.qtyFriendsPostcards);
            cv.put(Dashboard.QTY_JOURNAL,            di.qtyFriendsJournal);
            cv.put(Dashboard.QTY_VIDEOS,             di.qtyFriendsVideos);
            
//            cv.put(MyInbox.LAST_SYNC_LOCATION, city);
//            cv.put(MyInbox.LAST_SYNC_TIME, System.currentTimeMillis());
            
            cr.insert(Dashboard.CONTENT_URI, cv);
            
            //update sync
            PhonebookSharingManager.updateSyncStatus(cr, syncInProgress, Sync.STATUS_SUCCESS);
            
            publishProgress(0);//if went well
            
        } catch (IOException e) {
            Log.e(Global.LOG_TAG, "are you connected to internet???"); //TODO: send it to user
            PhonebookSharingManager.updateSyncStatus(cr, syncInProgress, Sync.STATUS_FAILURE);
            e.printStackTrace();
            cancel(true);
        } catch (Exception e) {
            PhonebookSharingManager.updateSyncStatus(cr, syncInProgress, Sync.STATUS_FAILURE);
            e.printStackTrace();
            cancel(true);
        }
        return null;
    }
    
    @Override
    public void onPostExecute(Void aVoid) {
//        pref = null;
        cx.startService(new Intent(cx, DesktopDashboardUpdaterService.class));
        cx.startService(new Intent(cx, NotSharingUpdaterService.class));
    }
}